﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Windows.Markup;
using System.Windows.Media.Imaging;
using CommunitySystem.Common;

namespace CommunitySystem.PageView.AdvancedCustomerQuery
{
    public partial class ColSelectWindow : ChildWindow
    {
        private CustomerQuery.Query_CustomerQuery _CustomerQuery = null;
        private System.Collections.ObjectModel.ObservableCollection<CommunitySystem.CustomerQuery.Query_ColumnCollection> _source = null;
        private CustomerQuery.CustomerQueryClient client = null;
        public ColSelectWindow(System.Collections.ObjectModel.ObservableCollection<CommunitySystem.CustomerQuery.Query_ColumnCollection> source, CustomerQuery.Query_ColumnsSelection entity, CustomerQuery.Query_CustomerQuery CustomerQuery)
        {
            InitializeComponent();
            _source = new System.Collections.ObjectModel.ObservableCollection<CustomerQuery.Query_ColumnCollection>();
            _CustomerQuery = CustomerQuery;
            //foreach (var i in source)
            //{
            //   // if (CustomerQuery.RowSelection.Where(c => c.ColumnID == i.ID).Count() == 0 && CustomerQuery.ColumnSelection.Where(c => c.ColumnID == i.ID).Count() == 0)
            //        _source.Add(i);
            //}
            _source = source;
            client = new CustomerQuery.CustomerQueryClient();
            client.GetValuesCompleted += new EventHandler<CustomerQuery.GetValuesCompletedEventArgs>(client_GetValuesCompleted);
            cb.ItemsSource = _source;
            cbLevel.ItemsSource = new
        string[5] { "第一级", "第二级", "第三级", "第四级", "第五级" };
            
        }
        //private ObservableCollection<CommunitySystem.CustomerQuery.Query_ColumnValue> _currentCollection = null;
        void client_GetValuesCompleted(object sender, CustomerQuery.GetValuesCompletedEventArgs e)
        {
            lbvalues.Columns.Clear();
            lbvalues.ItemsSource = null;

            string type = e.UserState as string;
            result.values = e.Result;
            DataGridTextColumn tc = new DataGridTextColumn() { Header = "显示名称", Binding = new System.Windows.Data.Binding() { Path = new PropertyPath("DisplayName"), Mode = System.Windows.Data.BindingMode.TwoWay } };
            lbvalues.Columns.Add(tc);
            string dtString = @" <DataTemplate xmlns='http://schemas.microsoft.com/client/2007'>
<ComboBox Name=""cbCompetor"" DisplayMemberPath=""Name"" SelectedValuePath=""Sign"" SelectedValue=""{Binding CompetorWay, Mode=TwoWay}""   Width=""80"" />
</DataTemplate>";
            DataTemplate dt = (DataTemplate)XamlReader.Load(dtString);
            DataGridTemplateColumn column = new DataGridTemplateColumn();
            column.Header = "匹配方式";
            column.CellTemplate = dt;

            //"字符型", "数字型", "日期型" 
            switch (type)
            {
                case "字符型":
                    lbvalues.Columns.Add(column);
                    lbvalues.Columns.Add(new DataGridTextColumn() { Header = "值", Binding = new System.Windows.Data.Binding() { Path = new PropertyPath("ColumnValue"), Mode = System.Windows.Data.BindingMode.TwoWay } });
                    break;
                case "数字型":
                    lbvalues.Columns.Add(new DataGridTextColumn() { Header = "起始值", Binding = new System.Windows.Data.Binding() { Path = new PropertyPath("StartInt"), Mode = System.Windows.Data.BindingMode.TwoWay } });
                    lbvalues.Columns.Add(column);
                    lbvalues.Columns.Add(new DataGridTextColumn() { Header = "终止值", Binding = new System.Windows.Data.Binding() { Path = new PropertyPath("EndInt"), Mode = System.Windows.Data.BindingMode.TwoWay } });
                    break;
                case "日期型":
                    dt = LayoutRoot.Resources["tempDateS"] as DataTemplate;                   
                     DataGridTemplateColumn columnDateS = new DataGridTemplateColumn();
                     columnDateS.Header = "起始值";
                     columnDateS.CellTemplate = dt;
                     lbvalues.Columns.Add(columnDateS);
                    lbvalues.Columns.Add(column);
                    dt = LayoutRoot.Resources["tempDateE"] as DataTemplate;
                     columnDateS = new DataGridTemplateColumn();
                     columnDateS.Header = "终止值";
                     columnDateS.CellTemplate = dt;
                     lbvalues.Columns.Add(columnDateS);     
                    break;
            }
            dtString = @"<DataTemplate xmlns='http://schemas.microsoft.com/client/2007'>
<Image   Name=""img""   />
</DataTemplate>";
            dt = (DataTemplate)XamlReader.Load(dtString);
            column = new DataGridTemplateColumn();
            column.Header = " ";
            column.CellTemplate = dt;
            lbvalues.Columns.Add(column);
            lbvalues.ItemsSource = result.values;
        }

        //private CustomerQuery.Query_ColumnsSelection _entity = null;
       

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (result.values.Where(c => string.IsNullOrEmpty(c.CompetorWay)).Count() > 0)
            {
                SilverlightMessageBoxLibrary.Message.
                    ErrorMessage("纬度" + result.values.Where(c => string.IsNullOrEmpty(c.CompetorWay)).FirstOrDefault().DisplayName + "必须选择匹配符");
                return;
            }

            if (result.ColumnLevel <= 0)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("必须选择列纬度的级别");
                return;
            }
            if (result.ColumnLevel > 1 && _CustomerQuery.ColumnSelection.Where(c => c.ColumnLevel == result.ColumnLevel - 1).Count() <= 0)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("列纬度未选择第" + (result.ColumnLevel - 1) + "级，不能选择第" + result.ColumnLevel + "级");
                return;
            }
            if (result == null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("必须选择一个纬度!");
                return;
            }
            if (result.values == null || result.values.Count<= 0)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("所选纬度至少有一个值!");
                return;
            }
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        public CommunitySystem.CustomerQuery.Query_ColumnsSelection result = null;
        private string _CurrentType = string.Empty;
        private void cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cb != null && cb.SelectedItem != null)
            {
                //var item = (sender as ComboBox).Tag as CustomerQuery.Query_ColumnValue;
                //if(item != null)
                //    item.CompetorWay = (sender as ComboBox).SelectedItem.ToString();
                CommunitySystem.CustomerQuery.Query_ColumnCollection item = cb.SelectedItem as CommunitySystem.CustomerQuery.Query_ColumnCollection;
                result = new CustomerQuery.Query_ColumnsSelection() { ColumnID = item.ID, ColumnType = item.Type, ColumnCode = item.ColumnCode, ColumnName = item.ColumnName, ColumnOrRow = "column", ColumnTable = item.ColumnTable };
                if (item != null)
                {
                    _CurrentType = item.Type;
                    client.GetValuesAsync(item.Type, item.RangeSQL, EHR.Common.Session.LoginUser.LoginName, item.Type);

                }
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = (sender as Image).Tag as CustomerQuery.Query_ColumnValue;
            if (item != null)
            {
                result.values.Remove(item);
            }
            
        }

        private void ibAdd_Click(object sender, RoutedEventArgs e)
        {
            if ( result != null &&result.values != null)
            {
                result.values.Add(new CustomerQuery.Query_ColumnValue() { ColumnSelectionID = result.ID });
            }
        }

        private void lbvalues_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            int index = lbvalues.Columns.Count - 1;

            Image img = lbvalues.Columns[index].GetCellContent(e.Row).FindName("img") as Image;
            if (img != null)
            {
                img.Source = new BitmapImage(new Uri("/CommunitySystem;component/Images/ViewDesign/delete.png", UriKind.RelativeOrAbsolute));
                img.Tag = result.values[e.Row.GetIndex()];
                img.MouseLeftButtonDown -= new MouseButtonEventHandler(Image_MouseLeftButtonDown);
                img.MouseLeftButtonDown += new MouseButtonEventHandler(Image_MouseLeftButtonDown);
            }
            ComboBox cb = null;
            switch (_CurrentType)
            {
                case "字符型":
                    cb = lbvalues.Columns[1].GetCellContent(e.Row).FindName("cbCompetor") as ComboBox;                   
                    cb.ItemsSource = QueryValueCompetor.StringCompetors;
                    break;
                case "数字型":
                case "日期型":
                    cb = lbvalues.Columns[2].GetCellContent(e.Row).FindName("cbCompetor") as ComboBox;
                    cb.ItemsSource = QueryValueCompetor.DateIntCompetors;
                    break;
            }
            cb.IsTabStop = true;
        }

        
        private void cb_SelectionChanged2(object sender, SelectionChangedEventArgs e)
        {
            if (cb != null && cb.SelectedItem != null)
            {
                //var item = (sender as ComboBox).Tag as CustomerQuery.Query_ColumnValue;
                //if (item != null)
                //    item.CompetorWay = (sender as ComboBox).SelectedItem.ToString();
            }
        }

        private void cbLevel_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (result != null && cbLevel.SelectedIndex >= 0)
            {
                result.ColumnLevel = cbLevel.SelectedIndex + 1;
            }
        }
    }
}

